﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows.Controls;
using System.Reflection;
using OpenExpressApp.MetaAttribute;
using Csla.Core;
using System.Windows.Data;
using OpenExpressApp.Module.WPF.Converter;
using System.Windows;
using OpenExpressApp.MetaModel;

namespace OpenExpressApp.Module.WPF.Editors
{
    /// <summary>
    /// 使用下拉实现的枚举属性编辑器
    /// </summary>
    public class EnumPropertyEditor : WPFPropertyEditor
    {
        private ComboBox _cb;

        public EnumPropertyEditor(BusinessObjectPropertyInfo propertyInfo, IObjectView view)
            : base(propertyInfo, view) { }

        protected override FrameworkElement CreateEditingElement()
        {
            this._cb = new ComboBox()
            {
                IsEditable = false,
                IsReadOnly = true,
                Name = PropertyInfo.Name
            };

            Binding textBinding = new Binding(PropertyInfo.Name);
            textBinding.Converter = new EnumConverter();
            this._cb.SetBinding(ComboBox.TextProperty, textBinding);

            //cb.Items.Clear();
            foreach (Enum item in Enum.GetValues(PropertyInfo.PropertyType))
            {
                this._cb.Items.Add(new EnumViewModel(item));
            }
            this._cb.SelectedValuePath = "EnumValue";
            this._cb.DisplayMemberPath = "Label";
            this._cb.SelectionChanged += new SelectionChangedEventHandler(cb_SelectionChanged);
            this._cb.DropDownOpened += new EventHandler(cb_DropDownOpened);

            return this._cb;
        }
        protected override void PrepareBinding(Binding binding)
        {
            base.PrepareBinding(binding);
            binding.Converter = new EnumConverter();
        }

        private void cb_DropDownOpened(object sender, EventArgs e)
        {
            if (IsReadOnly)
            {
                this._cb.IsDropDownOpen = false;
                return;
            }
        }
        private void cb_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (e.AddedItems.Count > 0)
            {
                var item = e.AddedItems[0] as EnumViewModel;
                if (null == item)
                {
                    e.Handled = true;
                    return;
                }
                PropertyValue = item.EnumValue;
            }
        }
    }
}